import React, {useEffect} from 'react';
import {requestGet} from "../../util/request";
import MysqlReplica from "./MysqlReplica";
import {Space, Tag} from "antd";
import LogFactory from "../../log/LogFactory";
import {MysqlStatusRollPolingTime} from "config/Setting";

const log = LogFactory.getLog("MysqlStateComponent");

const MYSQL_CONNECT_SUCCESS = "#0A0";
const MYSQL_CONNECT_FAILED = "#A00";
type MysqlColorType = "#0A0" | "#A00";

let awaitHandler: boolean = false;
const MysqlStateComponent = () => {
    const [mysqlIOColor, setMysqlIOColor] = React.useState<MysqlColorType>(MYSQL_CONNECT_FAILED);
    const [mysqlSQLColor, setMysqlSQLColor] = React.useState<MysqlColorType>(MYSQL_CONNECT_FAILED);
    const setMysqlStatusData = async () => {
        if(document.visibilityState === "hidden"){
            log.debug("窗口不可见,取消请求");
        }
        if (awaitHandler) {
            log.debug("上一次请求未完成,本次请求取消");
            return;
        }
        awaitHandler = true;
        const res = await requestGet<MysqlReplica>("/root/info/mysql");
        // log.debug("准备更新mysql状态显示组件数据",res) ;
        if (res.success) {
            const {slaveIORunning, slaveSQLRunning} = res.data;
            if (slaveSQLRunning === "Yes") {
                setMysqlSQLColor(MYSQL_CONNECT_SUCCESS);
            } else {
                setMysqlSQLColor(MYSQL_CONNECT_FAILED);
            }
            if (slaveIORunning === "Yes") {
                setMysqlIOColor(MYSQL_CONNECT_SUCCESS);
            } else {
                setMysqlIOColor(MYSQL_CONNECT_FAILED);
            }
        } else {
            log.error("获取mysql状态数据失败");
            setMysqlIOColor(MYSQL_CONNECT_FAILED);
            setMysqlSQLColor(MYSQL_CONNECT_FAILED);
        }
        awaitHandler = false;
    };

    useEffect(() => {
        setMysqlStatusData();
        const intervalId = setInterval(() => {
            setMysqlStatusData();
        }, MysqlStatusRollPolingTime);
        return () => {
            log.info("mysql状态显示组件卸载,清除定时器");
            clearInterval(intervalId);
        };
    }, []);
    return (
        // <Flex gap={5} justify={"center"} align={"start"} vertical={true}>
        <Space>
            <Tag color={mysqlIOColor}>MYSQL_IO</Tag>
            <Tag color={mysqlSQLColor}>MYSQL_SQL</Tag>
        </Space>
    );
};

export default MysqlStateComponent;